package com.jsgt.greekfire.viewmodel

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.fhx.core.base.BaseViewModel
import com.github.fujianlian.klinechart.KLineEntity
import com.jsgt.greekfire.bean.*
import com.jsgt.greekfire.common.http.safeLaunch
import com.jsgt.greekfire.common.util.TimeUtil
import com.jsgt.greekfire.repository.TradingRepository
import retrofit2.HttpException
import java.net.ConnectException
import java.net.SocketTimeoutException

class TradingViewModel: BaseViewModel(){
    private val tradingRepository = TradingRepository.instance

    val errorLiveData by lazy { MutableLiveData<Any>() }
    val entrustCoinListLiveData by lazy { MutableLiveData<List<EntrustCoin>>() }
    val tickMarketLiveData by lazy { MutableLiveData<TickMarket>() }
    val addUserEntrustLiveData by lazy { MutableLiveData<Any>() }
    val userEntrustLiveData by lazy { MutableLiveData<UserEntrust>() }
    val cancelUserEntrustLiveData by lazy { MutableLiveData<Any>() }
    val newPriceLiveData by lazy { MutableLiveData<NewPrice>() }
    val kLineEntityLiveData by lazy { MutableLiveData<List<KLineEntity>>() }
    val coinIntroduceLiveData by lazy { MutableLiveData<CoinIntroduce>() }
    val tickListLiveData by lazy { MutableLiveData<List<Tick>>() }

    private fun doError(error: Throwable) {
        if (error is SocketTimeoutException) {
            errorLiveData.value = "网络请求超时"
        } else if (error is ConnectException || error is HttpException) {
            errorLiveData.value = "网络请求失败"
        } else {
            errorLiveData.value = error.message
        }
    }
    
    /**
     * 交易对列表
     */
    fun getEntrustCoinList() {
        viewModelScope.safeLaunch {
            block = {
                val data = tradingRepository.getEntrustCoinList()
                if (data.code == 0) {
                    entrustCoinListLiveData.value = data.result
                } else {
                    errorLiveData.value = data
                }
            }
            onError = {
                errorLiveData.value = it.message
            }
        }
    }

    /**
     * 获取k线数据
     */
    fun getTickMarket(delKey: String) {
        viewModelScope.safeLaunch {
            block = {
                val data = tradingRepository.getTickMarket(delKey)
                if (data.code == 0) {
                    tickMarketLiveData.value = data.result;
                } else {
                    errorLiveData.value = data.msg
                }
            }
            onError = {
//                errorLiveData.value = it.message
                doError(it)
            }
        }
    }

    /**
     * 买入卖出交易
     */
    fun addUserEntrust(params: Map<String, Any>) {
        viewModelScope.safeLaunch {
            block = {
                val data = tradingRepository.addUserEntrust(params)
                if (data.code == 0) {
                    addUserEntrustLiveData.value = data.msg
                } else {
                    errorLiveData.value = data.msg
                }
            }
            onError = {
//                errorLiveData.value = it.message
                doError(it)
            }
        }
    }

    /**
     * 当前委托
     */
    fun getUserEntrust(params: Map<String, Any>) {
        viewModelScope.safeLaunch {
            block = {
                val data = tradingRepository.getUserEntrust(params)
                val page = params["page"]
                if (data.code == 0) {
                    if (userEntrustLiveData.value != null && data.result?.list != null && page != 1) {
                        val userEntrustList = userEntrustLiveData.value!!.list
                        for (index in userEntrustList.size - 1 downTo 0) {
                            data.result.list.add(0, userEntrustList[index])
                        }
                        userEntrustLiveData.value = data.result
                    } else {
                        userEntrustLiveData.value = data.result
                    }
                } else {
                    errorLiveData.value = data.msg
                }
            }
            onError = {
//                errorLiveData.value = it.message
                doError(it)
            }
        }
    }


    /**
     * 取消委托
     */
    fun cancelUserEntrust(params: Map<String, Any>) {
        viewModelScope.safeLaunch {
            block = {
                val data = tradingRepository.cancelUserEntrust(params)
                if (data.code == 0) {
                    val guid = params["guid"]
                    userEntrustLiveData.value?.list?.forEach {
                        if (guid == it.guid) {
                            val userEntrust = userEntrustLiveData.value
                            val userEntrustList: MutableList<UserEntrustItem> =
                                userEntrust!!.list.toMutableList()
                            userEntrustList -= it
                            userEntrust.list = userEntrustList
                            userEntrustLiveData.value = userEntrust
                            return@forEach
                        }
                    }
                    cancelUserEntrustLiveData.value = data.msg
                } else {
                    errorLiveData.value = data.msg
                }
            }
            onError = {
//                errorLiveData.value = it.message
                doError(it)
            }
        }
    }

    /**
     * 获取最新价格
     */
    fun getNewPrice(delKey: String) {
        viewModelScope.safeLaunch {
            block = {
                val data = tradingRepository.getNewPrice(delKey)
                if (data.code == 0) {
                    newPriceLiveData.value = data.result
                } else {
                    errorLiveData.value = data.msg
                }
            }
            onError = {
//                errorLiveData.value = it.message
                doError(it)
            }
        }
    }

    /**
     * 获取GFT k线数据
     */
    fun getGFTKLineData(params: Map<String, Any>) {
        viewModelScope.safeLaunch {
            block = {
                val data = tradingRepository.getGFTKLineData(params)
                if (data.code == 0) {
                    val kLineEntityList = ArrayList<KLineEntity>()
                    data.result?.forEach {
                        val kLineEntity = KLineEntity()
                        kLineEntity.Open = it.openingPrice
                        kLineEntity.Close = it.closingPrice
                        kLineEntity.High = it.topPrice
                        kLineEntity.Low = it.floorPrice
                        kLineEntity.Volume = it.dealQuantity
                        kLineEntity.Date = TimeUtil.time2String(it.ktime, "HH:mm")
                        kLineEntityList += kLineEntity
                    }
                    kLineEntityLiveData.value = kLineEntityList
                } else {
                    errorLiveData.value = data.msg
                }
            }
            onError = {
//                errorLiveData.value = it.message
                doError(it)
            }
        }
    }

    /**
     * 获取GFT简介
     */
    fun getCoinIntroduce(delKey: String) {
        viewModelScope.safeLaunch {
            block = {
                val data = tradingRepository.getCoinIntroduce(delKey)
                if (data.code == 0) {
                    coinIntroduceLiveData.value = data.result
                } else {
                    errorLiveData.value = data.msg
                }
            }
            onError = {
//                errorLiveData.value = it.message
                doError(it)
            }
        }
    }

    /**
     * 获取GFT成交数据
     */
    fun getTickList(params: Map<String, Any>) {
        viewModelScope.safeLaunch {
            block = {
                val data = tradingRepository.getTickList(params)
                if (data.code == 0) {
                    tickListLiveData.value = data.result
                } else {
                    errorLiveData.value = data.msg
                }
            }
            onError = {
//                errorLiveData.value = it.message
                doError(it)
            }
        }
    }
}